package com.dp.util;

import java.io.BufferedInputStream;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.methods.GetMethod;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;

import com.dp.pojo.NewsVo;
import com.dp.pub.SysProperty;
import com.dp.service.impl3.NewsServiceImpl3;

public class GenerateNewsHtml implements Runnable {

	private static Logger logger = Logger.getLogger(GenerateNewsHtml.class);
	private static String  NEWS_TEMPLATE = "com/dp/template/news_template.html";
	@Autowired
	private NewsServiceImpl3 newsService;
	@Autowired
	private NewsVo news;
	private int type;
	private Map<String, String> m;
	public GenerateNewsHtml(NewsVo news,int type,Map<String, String> m) {
		this.news = news;
		this.type = type;
		this.m=m;
	}
    public GenerateNewsHtml(){}
	public void run() {
		this.generateHtml();
		// TODO Auto-generated method stub

	}

	
	public void generateHtml() {
		if (type <1){
			logger.info("Error type, don't execute generateHtml");
			return;
		} 
		switch (type) {
		case 1:
			generateNewsHtml(this.news,this.type);
			break;
		case 2:
			generateHdHtml(this.news,this.type);
			break;
		case 3:
			generateYpNewsHtml(this.news,this.type);
			break;
		default:
			break;
		}
		
	}

	private void generateYpNewsHtml(NewsVo news2, int type2) {

		String imageSizeStr = SysProperty.getPrep("ypnews_imagesize");
		String imageFormat = SysProperty.getPrep("hdnews_imageformat");
		String templatepath = SysProperty.getPrep("ypnews_webviewtemplatepath");
		if (null == templatepath ||"".equals(templatepath.trim())) return;
    	if(imageFormat == null || imageFormat.equals(""))
    		imageFormat = "png";
		String[] imageSizeAry = imageSizeStr.split(","); 
//		imageSizeAry[imageSizeAry.length] = 
		
		if(imageSizeAry != null&&imageSizeAry.length>0)
		{
			for(String imageSizeScale:imageSizeAry)
			{
				String screenWidHei = imageSizeScale.split("@")[0];
				JspToHtmlFile(news,screenWidHei,news.getContentHtml(),news.getContentHtml()+"_b_"+screenWidHei);
			}
		}
	
		
	}
	private void generateHdHtml(NewsVo news2, int type2) {

		String imageSizeStr = SysProperty.getPrep("hdnews_imagesize");
		String imageFormat = SysProperty.getPrep("hdnews_imageformat");
		String templatepath = SysProperty.getPrep("hdnews_webviewtemplatepath");
		if (null == templatepath ||"".equals(templatepath.trim())) return;
    	if(imageFormat == null || imageFormat.equals(""))
    		imageFormat = "png";
		String[] imageSizeAry = imageSizeStr.split(","); 
		if(imageSizeAry != null&&imageSizeAry.length>0)
		{
			for(String imageSizeScale:imageSizeAry)
			{
				String screenWidHei = imageSizeScale.split("@")[0];
				JspToHtmlFile(news,screenWidHei,news.getContentHtml(),news.getContentHtml()+"_b_"+screenWidHei);
			}
		}
	
		
	}
	private void JspToHtmlFile(NewsVo news2, String screenWidHei,
			String contentHtml, String string) {
		// TODO Auto-generated method stub
		
	}
	/*
	 * 按照数据库尺寸配置尺寸生成base64 html
	 */
	public void generateNewsHtml(NewsVo news, int type) {
		String imageSizeStr = SysProperty.getPrep("news_imagesize");
		String imageFormat = SysProperty.getPrep("news_imageformat");
		String templatepath = SysProperty.getPrep("news_webviewtemplatepath");
		String path = this.getClass().getClassLoader().getResource("/").getPath();
		if (null == templatepath ||"".equals(templatepath.trim())) {
			
			
			templatepath = path+NEWS_TEMPLATE;
		}else{
			boolean exists = (new File(templatepath)).exists();
			if (!exists) templatepath = path+NEWS_TEMPLATE;
		}
    	if(imageFormat == null || imageFormat.equals(""))
    		imageFormat = "png";
		String[] imageSizeAry = imageSizeStr.split(","); 
		//根据模板生成默认页面
		newsJspToHtmlFile(news,"default",news.getContentHtml(),templatepath);
		if(imageSizeAry != null&&imageSizeAry.length>0)
		{
			for(String imageSizeScale:imageSizeAry)
			{
				String screenWidHei = imageSizeScale.split("@")[0];
				newsJspToHtmlFile(news,screenWidHei,news.getContentHtml()+"l_b_"+screenWidHei,templatepath);
			}
		}
	}
	/**
	 * 根据本地模板生成静态页面
	 * 
	 * @param JspFile
	 *            jsp路经
	 * @param HtmlFile
	 *            html路经
	 * @return
	 */
	public boolean newsJspToHtmlFile(NewsVo news,String screenwidth,
			String HtmlFile,String templatepath) {

		String str = "";
		String sourcecontent = "";
		try {
			String tempStr = "";
			FileInputStream is = new FileInputStream(templatepath);// 读取模块文件
			BufferedReader br = new BufferedReader(new InputStreamReader(is,"utf-8"));
			while ((tempStr = br.readLine()) != null)
				str = str + tempStr;
			is.close();
			
			// 读取保存的html源文件
			String tempSource = "";
			FileInputStream sis = new FileInputStream(news.getContentHtml());
			BufferedReader sbr = new BufferedReader(new InputStreamReader(sis,"utf-8"));
			while ((tempSource = sbr.readLine()) != null)
				sourcecontent = sourcecontent + tempSource;
			sis.close();
			
		} catch (IOException e) {
			e.printStackTrace();
			return false;
		}
		try {
			
			sourcecontent = replaceHtmlcss(sourcecontent);//处理内容中html标签属性(width,height)
			// 替换掉模块中相应的地方
			str = str.replaceAll("###title###", news.getContentName());
			str = str.replaceAll("###content###", sourcecontent);
			str = str.replaceAll("###source###", news.getPubCompany());
			str = str.replaceAll("###time###", (new java.text.SimpleDateFormat("yyyy年MM月dd日 ")).format(news.getLastupdatetime()));
//			str = replaceHtmlcss(str);//处理html标签属性(width,height)
			if (screenwidth.equals("default")){
				//html 录入源文件保存为*.htm, 根据模板生成一份格式化的*.html文件
				File f = new File(HtmlFile+"l");
				//BufferedWriter o = new BufferedWriter(new FileWriter(f));
				BufferedWriter o = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(f),"utf-8"));
				o.write(str);
				o.close();
				return true;
			}
			String one="";
			String tmp="";
			Pattern pimg = Pattern.compile("<img .*? />");
			Matcher mimg = null;
			mimg = pimg.matcher(str);
			while (mimg.find()){
				//one=  <img ... />
				one = mimg.group();
				
				//如果有style height width 则删除 
				if(one.contains("style=") || one.contains("STYLE="))
				{
					tmp = one.replaceAll("style=\".*?\"", "");
					str = str.replace(one, tmp);
					one = one.replaceAll("style=\".*?\"", "");
				}
				if(one.contains("height=") || one.contains("HEIGHT=") || one.contains("width=") || one.contains("WIDTH="))
				{
					tmp = one.replaceAll("height=\".*?\"", "");
					str = str.replace(one, tmp);
					one = one.replaceAll("height=\".*?\"", "");
					tmp = one.replaceAll("width=\".*?\"", "");
					str = str.replace(one, tmp);
				}
				
				String imgReg = "(src)=(\\s*(\"|'|))?\\s*([^\\>\\s]*?)(\\s*\"|'\\s*)";//用于在网页代码Content中查找匹配的图片链接。
				
				Pattern pattern = Pattern.compile(imgReg);//java.util.regex.Pattern
				Matcher matcher = pattern.matcher(one);     //java.util.regex.Matcher
				while (matcher.find()) {
					String hurl = matcher.group(4);
					logger.debug("get  image url : "+hurl);
				   String filename = hurl.substring(hurl.lastIndexOf("/")+1);
					
					logger.debug("getHtmlAttachments, filename: "+filename);
					String filepath="";
					String ext="";
					if(filename.indexOf(".") != -1){
						filepath = hurl.substring(0,hurl.lastIndexOf("."));
						ext = filename.substring(filename.lastIndexOf(".")+1);
						String url=filename.substring(0,filename.lastIndexOf("."));
						if(m.get(url)!=null){
							ext=m.get(url);
						}
						if (ext.equalsIgnoreCase("jpg") || ext.equalsIgnoreCase("png")|| ext.equalsIgnoreCase("gif")|| ext.equalsIgnoreCase("bmp")|| ext.equalsIgnoreCase("jpeg")){
							String hurl_screen = filepath+"_"+screenwidth+"."+ext;
							logger.debug("base 64 image path: "+hurl_screen);
							String imgbase64 =getPicBASE64(hurl_screen);
//							logger.info("base 64 image: "+imgbase64);
							if ("".equals(imgbase64) ||null ==imgbase64){
								str = str.replaceAll(one, "");
							}
							str = str.replaceAll(hurl, "data:image/"+ext+";base64,"+imgbase64);
						}
						
					}
//					str = str.replaceAll(one,"<a href='"+hurl+"'>"+one+"</a>");
				}
				
				
			}
		
			File f = new File(HtmlFile);
			BufferedWriter o = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(f),"utf-8"));
			o.write(str);
			o.close();
			
		} catch (IOException e) {
			e.printStackTrace();
			return false;
		}
		return true;
	}

	/**
	 * Gets the pic bas e64. 图片生成base64编码
	 * 
	 * @param picPath
	 *            the pic path
	 * @return the pic bas e64
	 */
	public static String getPicBASE64(String picurl) {
		
		if (null ==picurl || "".equals(picurl.trim())) return "";
		try {
			String uploadpath = SysProperty.getPrep("uploadpath");
			String downloadurl = SysProperty.getPrep("video_downloadurl");
			if(picurl.startsWith(downloadurl)){
				picurl=picurl.replace(downloadurl, uploadpath+"/");
				File imgfile=new File(picurl);
				if(imgfile.exists()){
					FileInputStream is=new FileInputStream(imgfile);
					int length=is.available();
					byte[] bytes=new byte[length];
					int i=is.read(bytes);
					is.close();
					if(i>0){
						return  new sun.misc.BASE64Encoder().encode(bytes); // 具体的编码方法
					}else{
						return "";
					}
				}else{
					picurl=picurl.replace(uploadpath+"/",downloadurl);
				}
				
			}
			HttpClient client = new HttpClient();
	        GetMethod get = new GetMethod(picurl);
	        client.executeMethod(get);
	        byte[] bytes =  get.getResponseBody();
	        int code = get.getStatusCode();
	        if (code !=200){
	        	return "";
	        }
			return new sun.misc.BASE64Encoder().encode(bytes); // 具体的编码方法
		} catch (Exception e) {
			e.printStackTrace();
		}
		return "";
	}

	//处理html标签属性(width,height)
	private static String replaceHtmlcss(String newsHtml) {
		if(newsHtml.contains("height=") || newsHtml.contains("HEIGHT=") || newsHtml.contains("width=") || newsHtml.contains("WIDTH="))
		{
			newsHtml = newsHtml.replaceAll("height=['\"].*?['\"]", "");
			newsHtml = newsHtml.replaceAll("HEIGHT=['\"].*?['\"]", "");
			newsHtml = newsHtml.replaceAll("width=['\"].*?['\"]", "");
			newsHtml = newsHtml.replaceAll("WIDTH=['\"].*?['\"]", "");
		}
		Pattern pattern = Pattern.compile("(style)=(\\s*(\"|'|))(.*?)(\\s*\"|'\\s*)");
		Matcher matcher = pattern.matcher(newsHtml);
		String tmp = "";
		String tmp1 = "";
		while(matcher.find()) {
			tmp = matcher.group(4);
			if(newsHtml.contains("height:") || newsHtml.contains("HEIGHT:") || newsHtml.contains("width:") || newsHtml.contains("WIDTH:")){
				tmp1 = tmp.replaceAll("height", "aaa");
				tmp1 = tmp1.replaceAll("HEIGHT", "aaa");
				tmp1 = tmp1.replaceAll("width", "aaa");
				tmp1 = tmp1.replaceAll("WIDTH", "aaa");
				newsHtml = newsHtml.replace(tmp, tmp1);
			}
		}
		
		//parse <a><img>
		String tmpaimg = "";
		String oldstr = "";
		Pattern paimg = Pattern.compile("<a.*?href=\".*?\"><img.*?></a>");
		Matcher maimg = paimg.matcher(newsHtml);
		Pattern pa = Pattern.compile("<a.*?href=\".*?\">");
		Matcher ma = null;
		if(newsHtml != null && newsHtml.length()>0)
		{
			while (maimg.find())
			{
				tmpaimg = maimg.group();
				oldstr = tmpaimg;
				ma = pa.matcher(tmpaimg);
				if(ma.find())
				{
					String tmpa = ma.group();
					tmpaimg = tmpaimg.replaceAll(tmpa, "");
					tmpaimg = tmpaimg.replaceAll("</a>", "");
				}
				newsHtml = newsHtml.replace(oldstr, tmpaimg);
		    }
		}
		return newsHtml;
	}
	
	public static void main(String[] args) {

		GenerateNewsHtml gh = new GenerateNewsHtml();
		System.out.println(gh.getPicBASE64("http://220.194.62.242/unisk_video/1000013/1/201101/ssnzgimkdgzu.jpg"));
	}
}
